/**
 * Created by zhangwenzhuo on 2016/7/8.
 */

var logger = require('log4js').getLogger();
var messageBroker = require('./messageBroker.js');

var socketserver = {};
socketserver.sockets = [];
socketserver.server = function(server, sessionMiddleWare){
    var io = require('socket.io')(server);
    var sockets = socketserver.sockets;
    logger.info("socket server created");
    io.on('connection', function (socket) {
        var req = socket.request;
        logger.info("request for connect");
        sessionMiddleWare(req, {}, function(){
            var session = req.session;
            if(session && session.user){
                logger.info(session.user.shortid + ' connected');
                socket.user = session.user;
                socket.on('disconnect', function () {
                    sockets.splice(sockets.indexOf(socket), 1);
                    logger.info('disconnect, sockets count  : ' + sockets.length);
                });
                sockets.push(socket);
                logger.info('current sockets count  : ' + sockets.length );
                socket.emit('connected');
            } else {
                logger.info("connection validate failed");
                //socket.disconnect('abc');
            }
        });
        socket.on('disconnection', function () {
            //socket断开后，取消所有相关的订阅 需要判断是否真正断开
            //messageBroker.disorderAll({'socketID':socket.id});
            logger.info("连接断开");

        });
        //监听订阅、取消订阅事件
        socket.on('disorder',function(data){
            //将data.socket_id 从data.msgName 的消息列表中删除
            messageBroker.disorder(data)
        });

        socket.on('order',function(data){
            //将data.socket_id 添加到 data.msgName 的消息列表中
            messageBroker.order(data)

        });

    });
};


module.exports = socketserver;